<template>
  <div class="class-detail-container" v-loading="isLoading">
    <el-page-header @back="goBack" :content="classDetail?.name || '班级详情'"></el-page-header>
    <el-divider></el-divider>

    <el-row :gutter="20">
      <!-- 左侧: 班级信息和学生管理 -->
      <el-col :span="16">
        <!-- 班级基础信息卡片 -->
        <ClassInfoCard
          :class-detail="classDetail"
          :is-teacher-owner="isTeacherOwner"
          :teacher-name="teacherName"
          :teacher-name-loading="teacherNameLoading"
          @edit="goToEditClass"
          @delete="handleDeleteClass"
        />

        <!-- 学生管理表格 (仅教师所有者可见) -->
        <StudentManager
          v-if="isTeacherOwner"
          :students="students"
          :loading="studentsLoading"
          v-model:current-page="studentListPage.current"
          v-model:page-size="studentListPage.size"
          @remove-student="handleRemoveStudent"
          @show-add-student="showAddStudentDialog = true"
          style="margin-top: 20px;"
        />
      </el-col>

       <!-- 右侧: 教师操作区 (仅教师所有者可见) -->
      <el-col :span="8" v-if="isTeacherOwner">
        <TeacherActionsPanel
            :invite-info="inviteInfo"
            :stats="stats"
            :loading="isLoading"
            :generating-code="isGeneratingCode"
            :refreshing-stats="isRefreshingStats"
            @generate-code="generateCode"
            @refresh-stats="fetchStats"
        />
      </el-col>

    </el-row>

    <!-- 添加学生对话框 -->
    <el-dialog v-model="showAddStudentDialog" title="添加学生到班级" width="500">
        <el-form @submit.prevent="handleAddStudentSubmit">
            <el-form-item label="学生ID或用户名">
                 <el-input v-model="studentToAdd" placeholder="请输入要添加的学生ID或用户名"></el-input>
                 <p class="input-tip">提示：请输入准确的学生ID。</p>
            </el-form-item>
        </el-form>
        <template #footer>
             <span class="dialog-footer">
                <el-button @click="showAddStudentDialog = false">取消</el-button>
                <el-button type="primary" @click="handleAddStudentSubmit" :loading="isAddingStudent">
                    确认添加
                </el-button>
             </span>
        </template>
    </el-dialog>

  </div>
</template>

<script setup>
/* global defineProps */
import { ref, computed, watch, reactive } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
// 导入子组件
import ClassInfoCard from '@/components/class/ClassInfoCard.vue';
import StudentManager from '@/components/class/StudentManager.vue';
import TeacherActionsPanel from '@/components/class/TeacherActionsPanel.vue';

const props = defineProps({ id: { type: [String, Number], required: true } });
const store = useStore();
const router = useRouter();

// --- 状态和计算属性 ---
// 主要加载状态
const isLoading = computed(() => store.state.class.isLoading);
// 子项加载状态
const teacherNameLoading = ref(false);
const studentsLoading = ref(false);
const isGeneratingCode = ref(false); // 用于生成邀请码按钮 loading
const isRefreshingStats = ref(false); // 用于刷新统计按钮 loading
const isAddingStudent = ref(false); // 添加学生操作 loading
const studentToAdd = ref(''); // 重新添加用于输入框

// 数据
const classDetail = computed(() => store.getters['class/getCurrentClassDetail']);
const students = computed(() => store.getters['class/getCurrentClassStudents']);
const stats = computed(() => store.getters['class/getCurrentClassStats']);
const inviteInfo = computed(() => store.getters['class/getCurrentInviteCode']);
const currentUserInfo = computed(() => store.getters.getUserInfo);
const isTeacher = computed(() => store.getters.isTeacher);
const teacherName = ref(null);

// 权限
const isTeacherOwner = computed(() => {
    return isTeacher.value && classDetail.value && currentUserInfo.value && classDetail.value.teacherId === currentUserInfo.value.id;
});

// 学生列表分页和搜索
const studentListPage = reactive({
    current: 1,
    size: 10,
});

// 添加学生对话框
const showAddStudentDialog = ref(false);


// --- 方法 ---

// 获取教师名称
const fetchTeacherName = async (teacherId) => {
    if (!teacherId) return;
    teacherNameLoading.value = true;
    teacherName.value = null;
    try {
        const user = await store.dispatch('fetchUserById', teacherId);
        if (user) {
            teacherName.value = user.fullName || user.username;
        }
    } catch (error) { /* ... */ }
    teacherNameLoading.value = false;
};

// 获取班级详情
const fetchDetails = async () => {
    // 不再直接控制 isLoading，让 action 控制模块的 isLoading
    await store.dispatch('class/fetchClassDetail', props.id);
    if (classDetail.value?.teacherId) {
        await fetchTeacherName(classDetail.value.teacherId);
    }
    if(isTeacherOwner.value) {
        await fetchStudents();
        await fetchStats();
    }
};

// 获取学生列表
const fetchStudents = async () => {
    studentsLoading.value = true;
    await store.dispatch('class/fetchClassStudents', {
        classId: props.id,
        page: studentListPage.current,
        size: studentListPage.size,
        // query: studentListPage.query, // 如果需要搜索功能，在这里添加
    });
    studentsLoading.value = false;
};

// 获取统计信息
const fetchStats = async () => {
    isRefreshingStats.value = true;
    await store.dispatch('class/fetchClassStatistics', props.id);
    isRefreshingStats.value = false;
};

// 生成邀请码
const generateCode = async () => {
    isGeneratingCode.value = true;
    await store.dispatch('class/generateInviteCode', props.id);
    isGeneratingCode.value = false;
};

// 跳转到编辑页
const goToEditClass = () => {
    router.push({ name: 'ClassEdit', params: { id: props.id } });
};

// 删除班级
const handleDeleteClass = async () => {
    // 可选：添加 ElMessageBox 确认
    // await ElMessageBox.confirm('此操作将永久删除该班级及其相关数据, 是否继续?', '警告', { type: 'warning' });
    const result = await store.dispatch('class/deleteClass', props.id);
    if(result.success) {
        router.replace({ name: 'ClassList' });
    }
};

// 移除学生
const handleRemoveStudent = async (studentId) => {
    await store.dispatch('class/removeStudentFromClass', { classId: props.id, studentId });
};

// 提交添加学生
const handleAddStudentSubmit = async () => {
    if (!studentToAdd.value) {
        ElMessage.warning('请输入学生ID或用户名');
        return;
    }
    // --- 重要: 假设输入的是学生 ID --- 
    // 实际应用中可能需要后端支持通过用户名查找或前端先查找再提交ID
    const studentIdToAdd = parseInt(studentToAdd.value.trim());
    if (isNaN(studentIdToAdd)) {
        ElMessage.error('请输入有效的学生ID');
        return;
    }
    // ---------------------------------

    isAddingStudent.value = true;
    await store.dispatch('class/addStudentToClass', { classId: props.id, studentId: studentIdToAdd });
    isAddingStudent.value = false;
    // 清空输入框
    studentToAdd.value = ''; 
    // 如果添加成功，列表会在 action 中自动刷新，但如果需要立即关闭弹窗：
    // 考虑在 action 返回成功状态后关闭弹窗
    // showAddStudentDialog.value = false; 
};

// 返回
const goBack = () => router.back();

// --- 生命周期和监听器 ---

// 监听学生分页变化
watch([() => studentListPage.current, () => studentListPage.size], () => {
    if(isTeacherOwner.value) { // 仅在教师视图下需要监听分页变化
        fetchStudents();
    }
});

// 监听路由 ID 变化
watch(() => props.id, (newId, oldId) => {
  if (newId && newId !== oldId) {
    teacherName.value = null;
    // 重置学生列表分页
    studentListPage.current = 1;
    studentListPage.size = 10;
    fetchDetails();
  }
}, { immediate: true });

</script>

<style scoped>
.class-detail-container {
  padding: 20px;
}
.el-page-header {
    margin-bottom: 20px;
}
.el-divider {
    margin: 20px 0;
}
/* 添加学生对话框内的样式 */
.el-select {
    width: 100%;
}
.input-tip {
    font-size: 12px;
    color: #909399;
    line-height: 1.4;
}
</style> 